define(function (require, exports, module) {
    var template = require("template");
    var Ajax = require("ajax");
    var layer = require("layer");
    var pagination = require('pagination');
    var util = require('util');
    
    var collectObj = function (callback) {
        this.init.apply(this,arguments);
    };
    collectObj.prototype = {
        constructor: collectObj,
        options: {},
        init: function (options) {
            var t = this;
            t.options = $.extend({},t.options,options);
            $(".tipConNav").text("收藏");
            $(window).off('scroll');
            $("#rightConBox").html(template("monitorTemp",{}));
            t.mask();
            t.queryInformation();
            t.loadInitList(1);
            t.isCollectionEvent();
            t.loadWeixinEvent();
			//滚动条置顶
			window.scrollTo(0,0);
        },
        mask: function(){
            $(".mask").css("height",$(document).height());
            $(".mask").css("width",$(document).width());
        },
        
        loadInitList: function(pageIndex) {
			var t = this;
			Ajax.ajax({
				url: localhost+"enshrine/selectAll.do",
				data: {
					pageIndex: pageIndex,
					title: $("#search_input").val()?$("#search_input").val().trim():null
				},
				beforeSend: function() {
					if(pageIndex==1){
						$('#collect_table>tbody').html(template("loadingDom"));
					}else{
						$("#listDom").html('');
						$("#listDom").append("<div class='loadingMoreBox animated fadeIn nextloding'><span>正在加载中，请稍后</span></div>");
					}
				},
				success: function(data) {
    				//防止失效的请求影响到下次页面的滚动加载
    				var href = window.location.href.indexOf("admin/collect");
    				if(href < 0 ) {
    					return;
    				}
					if(data.returnCode == 10000){
						if(data.returnData && data.returnData.length > 0) {
							$(".loadingBox").remove();
							$(".loadingMoreBox").remove();
							var tHead = '',tList= '',sourceName='',isCollection='',colors='', level='',dataList = data.returnData;
							
			                for (var i = 0; i < dataList.length; i++) {
			                    var item = dataList[i]; 
			                    if(item.isCollection==0){
			                    	isCollection = "收藏";
			                    }else{
			                    	isCollection = "取消收藏"
			                    }
//			                    if(item.articleType=="Micro"){
//			                    	sourceName = "微博";
//			                    }else if(item.articleType=="BBS"){
//			                    	sourceName = "论坛";
//			                    }else if(item.articleType=="WeiXin"){
//			                    	sourceName = "微信";
//			                    }else{
//			                    	sourceName = item.articleType;
//			                    }
			                    sourceName = item.articleType;
			                    if(!item.starLevel){
			                    	level = "";
			                    }else{
			                    	level = item.starLevel;
			                    }
			                    if(item.enshrineNature=="正面"){
			                    	colors="green";
			                    }else if(item.enshrineNature=="负面"){
			                    	colors="red";
			                    }
			                    //判断是否弹出浮层
			                    if(item.articleType=="微信"){
			                    	if(localStorage.getItem(item.articleId)!=null){
			                    		tList += '<tr><td><a class="changeColor" data-type="weixin" data-ifmId="'+ item.ifmId +'" data-articleId="'+ item.articleId +'" href="javascript:;">'+item.enshrineTitle+'</a></td>';
			                    	}else{
			                    		tList += '<tr><td><a data-type="weixin" data-ifmId="'+ item.ifmId +'" data-articleId="'+ item.articleId +'" href="javascript:;">'+item.enshrineTitle+'</a></td>';
			                    	}
			                    }else{
			                    	tList += '<tr><td><a target="_blank" href="' + item.enshrineUrl + '">'+item.enshrineTitle+'</a></td>';
			                    }
			                    //表格
			                    tList += "<td>"+ sourceName +
			                    		 "</td><td>"+ item.enshrineAuthor +
			                    		 "</td><td>"+ item.releaseTime +
			                    		 "</td><td class='"+ colors +"'>"+ item.enshrineNature +
			                    		 "</td><td>"+ level +
			                    		 "<td><a href='javascript:;' class='collect' data-nature='"+ item.enshrineNature +"'data-ifmid='"+ item.ifmId +"' data-articleid='"+ item.articleId+"'>"+isCollection+"</a></td>";
			                }
			                tHead = "<tr class='th'><th>标题</th><th>来源</th><th>作者</th><th>发布时间</th><th>性质</th><th>星级</th><th>收藏</th></tr>";
			                if(pageIndex==1){
			                	$('#collect_table>tbody').html('');
			                	$('#collect_table>tbody').append(tHead+tList);
			                }else{
			                	$('#collect_table>tbody').append(tList);
			                }
//			                util.CutOff();      //截断过长文字
			                if(href > -1 ) {
			                	t.loadPage(pageIndex);
			                }
			                if(!(pageIndex==1 && dataList.length<15)){
			                	$("#listDom").append("<div class='morePage animated fadeIn'><span>下拉加载更多</span></div>");
			                }
						} else {
							$(".loadingBox").remove();
							$(".loadingMoreBox").remove();
							$(window).off('scroll');
							if(pageIndex==1){
								$('#collect_table>tbody').html(template("noDataDom"));
							}else{
								$("#listDom").append("<div class='lastPage animated fadeIn'><span>没有更多内容</span></div>");
							}
						}
					}	
				}
			});
		},
		loadPage: function(pageIndex) {
			var t = this;
			//获取页面顶部被卷起来的高度
			function scrollTop() {
				return Math.max(
					//chrome
					document.body.scrollTop,
					//firefox/IE
					document.documentElement.scrollTop);
			}
			//获取页面文档的总高度
			function documentHeight() {
				//现代浏览器（IE9+和其他浏览器）和IE8的document.body.scrollHeight和document.documentElement.scrollHeight都可以
				return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
			}
			function windowHeight() {
				return(document.compatMode == "CSS1Compat") ?
					document.documentElement.clientHeight :
					document.body.clientHeight;
			}
			if(window.location.href.indexOf("admin/collect")>-1){
			}else{
				return false;
			}
			var isloading = false;
			$(window).off('scroll');
			$(window).on('scroll', function() {
				//判定是否加载中，防止重复加载
				if(!isloading){
					//滚动条卷起来的高度 + 窗口高度 >= 文档的总高度 - 50/*这里将滚动响应区域高度取50px*/；如果这个判断为true则表示滚动条滚动到了底部。
					if(scrollTop() + windowHeight() >= (documentHeight() - 50)) {
						isloading = false;
						pageIndex = parseInt(pageIndex)+ 1;
						if(window.location.href.indexOf("admin/collect")>-1){//双重判断，解决跳转其它页面后的请求冲突
						}else{
							return false;
						}
						t.loadInitList(pageIndex);
						isloading = true;
					}
				}
			});
		},
		
        //方案查询
        queryInformation: function(){
            var t = this;            
        	$(".searchBtn").on('click',function(){
        		//防止重复滚动加载数据
        		$(window).off('scroll');
        		t.loadInitList(1);
        	});
            //键盘“enter”搜索
            $("#search_input").keydown(function(event) {
                if (event.keyCode == "13") {//keyCode=13是回车键
                	t.loadInitList(1);
                }
            });
        },
        
        //取消收藏
        isCollectionEvent: function(){
        	var t = this;
        	$('.monitor_table > tbody').delegate('.collect','click',function(){
        		$(this).removeClass('collect');
        		var articleId = $(this).attr("data-articleid");
        		var ifmId = $(this).attr("data-ifmid");
        		var params = {
        			articleId: articleId,
        			ifmId: ifmId
        		}
    			Ajax.ajax({
    				url: localhost + 'enshrine/delete.do',
    				data: params,
    				success: function(data) {
    					if(data.returnCode == 10000){
    						layer.msg(data.returnMessage,{time: 2000},function(){
    			        		$(window).off('scroll');
    			        		t.loadInitList(1);
    						});
    					} 
    				}
    			});
        	});
        },
        
        //微信操作
        loadWeixinEvent:function(){
            var t =this;
            $('.monitor_table>tbody').delegate('a', 'click', function () {
                var type = $(this).attr('data-type');
                if(type =="weixin"){
                    if(!$(this).hasClass("changeColor")){
                    	$(this).addClass("changeColor");
                    }
                    
                	var articleId = $(this).attr('data-articleId');
                	var ifmId = $(this).attr('data-ifmId');
                	
                	var params ={
                		articleId:articleId,
                		ifmId:ifmId
                	}
                	Ajax.ajax({
        				url: localhost + "Monitoring/findSingle.do",
        				data: params,
        				success: function(data) {
        					if(data.returnCode == 10000){
        	                    var title = data.returnData.title;
        	                    var author = data.returnData.author;
        	                    var releaseTime = data.returnData.releaseTime;
        	                    var source = data.returnData.source;
        	                    var content = data.returnData.content;
        	                    var reg = /\n/g;
        	                    content = content.replace(reg, '<br>');
        	                    layer.open({
        	                        title: '&nbsp;',
        	                        type: 1,
        	                        closeBtn: 1,
        	                        skin: 'inner_url',
        	                        content: "<div class='weixin_title'>" + title + "</div>" +"<div class='weixin_source'><span>"+ releaseTime+"</span><span>"+ author +"</span><span>"+ source+"</span></div><div class='weixin_content'>"+ content + "</div>",
        	                        area: ['80%', '650px'],
        	                        btn:['关闭'],
        	                        maxmin: false,
        	                        scrollbar: false, // 父页面 滚动条 禁止
        	                        shadeClose: true
        	                    });
        	                    localStorage.setItem(articleId, new Date().valueOf());
        					}
        				}
        			});
                }
            });
        }
		
    };
    module.exports = collectObj;
});

